package com.sunyw.xyz.service;

import com.sunyw.xyz.utils.ExcelUtils;
import com.sunyw.xyz.vo.PoiExcelBean;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

public class ExcelService {

    private static final String xlsx = ".xlsx";
    private static final String xls = ".xls";

    public static void main(String[] args) throws IOException {
        System.out.println("------------------------<开始进行excel解析>------------------------");
        PoiExcelBean bean = new PoiExcelBean();
        File file = new File("/21.xls");
        //File file = new File("D:/21.xls");
        String fileName = file.getName();
        //判断文件类型
        InputStream inputStream = new FileInputStream(file);
        String end_name = fileName.substring(fileName.lastIndexOf("."));
        Workbook wb;
        System.out.println("endname:" + end_name);
        if (xlsx.equals(end_name)) {
            /*xlsx格式需要使用 XSSFWorkbook对象进行解析*/
            wb = new XSSFWorkbook(inputStream);
            System.out.println("当前为xlsx格式开始解析");
        } else if (xls.equals(end_name)) {
            /*xls格式需要使用 HSSFWorkbook对象进行解析*/
            wb = new HSSFWorkbook(inputStream);
            System.out.println("当前为xls格式,开始解析");
        } else {
            System.out.println("文件格式错误");
            return;
        }
        //获取第一个sheet页,即excel下方的sheet
        Sheet sheet = wb.getSheetAt(0);
        //excel的角标读取时是从0开始,跟数组一样
        ExcelUtils utils = new ExcelUtils();
        String name = utils.getCellValue(2, 0, sheet);
        System.out.println("姓名:" + name);
        bean.setName(name);
        String age = utils.formatString(utils.getCellValue(2, 1, sheet));
        System.out.println("年龄:" + age);
        bean.setAge(age);
        String phone = utils.format(utils.getCellValue(2, 2, sheet));
        System.out.println("电话:" + phone);
        bean.setPhoneNumber(phone);
        String email = utils.getCellValue(2, 3, sheet);
        System.out.println("邮箱:" + email);
        bean.setEmail(email);
        String address = utils.getCellValue(2, 4, sheet);
        System.out.println("地址:" + address);
        bean.setAddress(address);
        System.out.println("对象信息为:[" + bean + "]");
        System.out.println("------------------------<excel解析完毕>------------------------");
    }

}
